package com.ferry.transport.netty.handler.client;

import com.ferry.common.util.StackTraceUtil;
import com.ferry.protocol.payload.ResponsePayload;
import com.ferry.transport.netty.channel.NettyChannel;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by daiyong
 */
@ChannelHandler.Sharable
public class ConnectorHandler extends ChannelInboundHandlerAdapter {
	private static final Logger logger = LoggerFactory.getLogger(ConnectorHandler.class);

	private ConsumerProcessor processor;

	public ConnectorHandler(ConsumerProcessor processor) {
		this.processor = processor;
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		Channel ch = ctx.channel();

		if (msg instanceof ResponsePayload) {
			try {
				processor.handleResponse(NettyChannel.attachChannel(ch), (ResponsePayload) msg);
			} catch (Throwable t) {
				logger.error("ConnectorHandler channelRead exception", t);
			}
		} else {
			ReferenceCountUtil.release(msg);
		}
	}
}
